﻿using System;
using System.Reflection;
using UnityEngine;

// 不允许同一对象上挂载相同脚本
[DisallowMultipleComponent]
public class SingletonAutoMono<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T mInstance;

    public static T Instance
    {
        get
        {
            if (mInstance == null)
            {
                // 先找一找
                GameObject findObj = GameObject.Find(typeof(T).Name);
                if (findObj != null)
                {
                    // 确保这个名字的对象上真有这个Component
                    mInstance = findObj.GetComponent<T>();
                }

                if (mInstance == null)
                {
                    // // 有公用构造器,会破环唯一性
                    // var ctors = typeof(T).GetConstructors(BindingFlags.Instance | BindingFlags.Public);
                    //
                    // if (ctors.Length > 0)
                    // {
                    //     throw new Exception("Public Constructor() found in " + typeof(T));
                    // }
                    
                    if (findObj == null)
                    {
                        // 动态创建和挂载
                        GameObject obj = new GameObject(typeof(T).Name);
                        mInstance = obj.AddComponent<T>();
                        // 场景切换不被移除
                        DontDestroyOnLoad(obj);
                    }
                    else
                    {
                        findObj.AddComponent<T>();
                        DontDestroyOnLoad(findObj);
                    }
                }
            }

            return mInstance;
        }
    }
}